import axios from "axios";
import { message } from "ant-design-vue";
const service = axios.create({
  baseURL: "/api",
  timeout: 50000,
});
service.interceptors.request.use(
  (config: any) => {
    if (config.headers["Content-Type"]) {
      config.headers["Content-Type"] = config.headers["Content-Type"];
    }
    config.headers["zstax-response"] = "standard";
    if (config.method === "get" && config.params) {
      let url = config.url + "?";
      for (const propName of Object.keys(config.params)) {
        const value = config.params[propName];
        const part = encodeURIComponent(propName) + "=";
        if (value !== null && typeof value !== "undefined") {
          if (typeof value === "object") {
            for (const key of Object.keys(value)) {
              const params = propName + "[" + key + "]";
              const subPart = encodeURIComponent(params) + "=";
              url += subPart + encodeURIComponent(value[key]) + "&";
            }
          } else {
            url += part + encodeURIComponent(value) + "&";
          }
        }
      }
      url = url.slice(0, -1);
      config.params = {};
      config.url = url;
    }
    return config;
  },
  (error: any) => Promise.reject(error)
);
service.interceptors.response.use(
  async (response: any) => {
    const code = response.data.code || 200;
    const msg = response.data.msg || response.data.message;
    const res = response.data;
    if (response.config != null && response.config.headers != null) {
      return res;
    }
    if (code === 401) {
      message.error(msg);
      return Promise.reject(new Error(msg));
    } else if (code === 500) {
      message.error(msg);
      return Promise.reject(new Error(msg));
    } else if (code !== 200) {
      message.error(msg);
      return Promise.reject(new Error(msg));
    } else {
      return res;
    }
  },
  (error: any) => {
    return Promise.reject(error);
  }
);
export default service;
